import type {
  PlasmoCSConfig,
  PlasmoCSUIJSXContainer,
  PlasmoCSUIProps,
  PlasmoRender
} from "plasmo"
import type { FC } from "react"
import { createRoot } from "react-dom/client"
import { Provider } from "react-redux"

import { PersistGate } from "@plasmohq/redux-persist/integration/react"

import { persistor, store } from "~store"

import "@Styles/jinritemai.scss"

import { Icon, message } from "@bytedance/mona-ui"
import React, { useState } from "react"

import FuncTabs from "./FuncTabs"

// 指定挂载站点
export const config: PlasmoCSConfig = {
  matches: ["https://fxg.jinritemai.com/*"]
}

// 获取抖店挂载节点
export const getRootContainer = () =>
  new Promise((resolve) => {
    const checkInterval = setInterval(() => {
      const rootContainerParent = document
        .querySelector(".app-content")
        .querySelector("[class*=styles_subAppContent]")
      if (rootContainerParent) {
        clearInterval(checkInterval)
        const rootContainer = document.createElement("div")
        rootContainer.id = "ShowContBox"
        rootContainerParent.insertBefore(
          rootContainer,
          rootContainerParent.firstChild
        )
        resolve(rootContainer)
      }
    }, 137)
  })

// 创建dom元素
const PlasmoOverlay: FC<PlasmoCSUIProps> = () => {
  const [showBotems, setShowBotems] = useState(true)
  // const [showBotems2, setShowBotems2] = React.useState(false)
  function cleartab() {
    // console.log("关闭窗口!")
    // document.getElementById("ShowContBox")?.remove()
    setShowBotems(false)
    message.success("临时关闭抖羚羊助手!")
  }
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        {showBotems && (
          <div className="topbox">
            <div className="cleariconbox">
              <div className="leftcontent">
                <FuncTabs />
              </div>
              <div className="rightcontent">
                <Icon
                  type="CloseIcon"
                  onClick={cleartab}
                  className="cleariconstyle"
                />
              </div>
            </div>
          </div>
        )}
      </PersistGate>
    </Provider>
  )
}
// const dow = <></>
// render
export const render: PlasmoRender<PlasmoCSUIJSXContainer> = async ({
  createRootContainer
}) => {
  if (!createRootContainer) return
  // console.log('渲染')
  const rootContainer = await createRootContainer()
  const root = createRoot(rootContainer)
  root.render(<PlasmoOverlay />)
  setInterval(async () => {
    // console.log("抖羚羊助手已启动! 定时检查是否安装上DOM")
    const ShowContBoxDom = document.getElementById("ShowContBox")
    // console.log(ShowContBoxDom)
    if (!ShowContBoxDom) {
      const rootContainer = await createRootContainer()
      const root = createRoot(rootContainer)
      root.render(<PlasmoOverlay />)
    }
  }, 2000)
}

export default PlasmoOverlay // PlasmoOverlay
